const express = require('express');
const cors = require('cors');
const helmet = require('helmet');
const rateLimit = require('express-rate-limit');
const path = require('path');
const authRoutes = require('./routes/auth');
const billRoutes = require('./routes/bills');
const { initDatabase } = require('./database/init');

const app = express();
const PORT = process.env.PORT || 3000;

// 安全中间件
app.use(helmet());
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// 速率限制
const limiter = rateLimit({
  windowMs: 15 * 60 * 1000, // 15分钟
  max: 100, // 限制每个IP 15分钟内最多100个请求
  message: '请求过于频繁，请稍后再试'
});
app.use('/api/', limiter);

// 登录限制
const loginLimiter = rateLimit({
  windowMs: 15 * 60 * 1000,
  max: 5,
  message: '登录尝试次数过多，请15分钟后再试'
});
app.use('/api/auth/login', loginLimiter);

// 静态文件服务
app.use(express.static(path.join(__dirname, '../frontend/dist')));

// API路由
app.use('/api/auth', authRoutes);
app.use('/api/bills', billRoutes);

// 初始化数据库
initDatabase();

// 启动服务器
app.listen(PORT, () => {
  console.log(`服务器运行在端口 ${PORT}`);
  console.log(`管理员账号: szllflxy`);
  console.log(`管理员密码: rongcheng16888A`);
});
